﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tunnel.DevicesControls;

namespace Tunnel.Tools.FcmsSupport
{
    public class Item
    {
        private ConnectIF connectIF = new ConnectIF();

        public void dispose()
        {
            this.connectIF.dispose();
        }

        public bool JX_DownloadFile(string filename, ref List<byte> downloadfile, string portname)
        {
            try
            {
                downloadfile.Clear();
                SerialPort port = new SerialPort();
                byte[] bytes = Encoding.ASCII.GetBytes(filename);
                List<byte> collection = new List<byte>();
                for (int i = 0; i < bytes.Length; i++)
                {
                    collection.Add(bytes[i]);
                }
                uint offset = 0;
                bool flag = true;
                while (flag)
                {
                    List<byte> list6 = new List<byte>();
                    list6.Add(2);
                    list6.Add(0x30);
                    list6.Add(0x30);
                    list6.Add(0x30);
                    list6.Add(0x39);
                    List<byte> buffer = list6;
                    buffer.AddRange(collection);
                    List<byte> list3 = new List<byte>();
                    list3 = this.connectIF.JX_GetOffSetbytes(offset);
                    buffer.AddRange(list3);
                    if (!this.connectIF.Get_CRC_Checked(ref buffer))
                    {
                        return false;
                    }
                    if (!this.connectIF.JX_EscapeString(ref buffer, 5))
                    {
                        return false;
                    }
                    buffer.Add(3);
                    List<byte> list4 = new List<byte>();
                    int num3 = 0;
                    while (num3 < 3)
                    {
                        if (!this.connectIF.JX_SendBySerialPort(ref port, buffer.ToArray(), portname))
                        {
                        }
                        else
                        {
                            List<byte> list5 = new List<byte>();
                            Thread.Sleep(200);
                            if ((this.connectIF.JX_ReceiveBySerialPort(ref port, portname, ref list5) && this.connectIF.JX_RecIsRight(ref list5, ref list4)) && (list4.Count < 0x800))
                            {
                                flag = false;
                                break;
                            }
                        }
                        num3++;
                    }
                    if (num3 == 3)
                    {
                        return false;
                    }
                    downloadfile.AddRange(list4);
                    offset += 0x800;
                }
                if (!this.connectIF.JX_CloseDev(ref port, portname))
                {
                    return false;
                }
                if (downloadfile.Count == 0)
                {
                    return false;
                }
                return true;
            }
            catch (Exception exception)
            {
                return false;
            }
        }


        public bool JX_GetBightness(ref List<byte> brightnessInfo, string portname)
        {
            try
            {
                SerialPort port = new SerialPort();
                List<byte> list3 = new List<byte>();
                list3.Add(2);
                list3.Add(0x30);
                list3.Add(0x30);
                list3.Add(0x30);
                list3.Add(0x36);
                List<byte> list = list3;
                if (!this.connectIF.Get_CRC_Checked(ref list))
                {
                    return false;
                }
                if (!this.connectIF.JX_EscapeString(ref list, 5))
                {
                    return false;
                }
                list.Add(3);
                byte[] frame = new byte[list.Count];
                for (int i = 0; i < list.Count; i++)
                {
                    frame[i] = list[i];
                }
                if (!this.connectIF.JX_SendBySerialPort(ref port, frame, portname))
                {
                    return false;
                }
                List<byte> list2 = new List<byte>();
                if (!this.connectIF.JX_ReceiveBySerialPort(ref port, portname, ref list2))
                {
                    return false;
                }
                if (!this.connectIF.JX_RecIsRight(ref list2, ref brightnessInfo))
                {
                    return false;
                }
                if (!this.connectIF.JX_CloseDev(ref port, portname))
                {
                    return false;
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }


        /// 发送文件
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="file"></param>
        /// <param name="PortName"></param>
        /// <returns></returns>
        public bool JX_UploadFile(string filename, ref List<byte> file, string PortName)
        {
            try
            {
                SerialPort port = new SerialPort();
                byte[] bytes = Encoding.ASCII.GetBytes(filename);
                List<byte> collection = new List<byte>();
                for (int i = 0; i < bytes.Length; i++)
                {
                    collection.Add(bytes[i]);
                }
                collection.Add(0x2b);
                uint offset = 0;
                bool flag = true;
                while (flag)
                {
                    List<byte> list7 = new List<byte>();
                    list7.Add(2);
                    list7.Add(0x30);
                    list7.Add(0x30);
                    list7.Add(0x31);
                    list7.Add(0x30);
                    List<byte> buffer = list7;
                    buffer.AddRange(collection);
                    List<byte> list3 = new List<byte>();
                    list3 = this.connectIF.JX_GetOffSetbytes(offset);
                    buffer.AddRange(list3);
                    List<byte> list4 = new List<byte>();
                    flag = this.connectIF.JX_GetFileSegment(ref file, out list4);
                    buffer.AddRange(list4);
                    if (!this.connectIF.Get_CRC_Checked(ref buffer))
                    {
                        return false;
                    }
                    if (!this.connectIF.JX_EscapeString(ref buffer, 5))
                    {
                        return false;
                    }
                    buffer.Add(3);

                    //将buffer的内容转化成为16进制字符串序列存于command
                    string command = "";
                    foreach(byte b in buffer)
                    {
                        command = command + b.ToString("x2");
                    }
                    command = command.ToUpper();

                    //此处插入将command插入数据库的程序

                    //插入结束

                    offset += 0x800;
                    buffer.Clear();
                }
                return true;
                
            }
            catch
            {
                return false;
            }
        }
        FCMSForm fcmsForm;
        public bool JX_UploadFile(string filename, ref List<byte> file, string fcmsId,string paramName,string controlSwitch,FCMSForm fcmsForm)
        {
            try
            {
                byte[] bytes = Encoding.ASCII.GetBytes(filename);
                List<byte> collection = new List<byte>();
                for (int i = 0; i < bytes.Length; i++)
                {
                    collection.Add(bytes[i]);
                }
                collection.Add(0x2b);
                uint offset = 0;
                bool flag = true;
                while (flag)
                {
                    List<byte> commandByte = new List<byte>();
                    commandByte.Add(2);
                    commandByte.Add(0x30);
                    commandByte.Add(0x30);
                    commandByte.Add(0x31);
                    commandByte.Add(0x30);
                    List<byte> buffer = commandByte;
                    buffer.AddRange(collection);
                    List<byte> list3 = new List<byte>();
                    list3 = this.connectIF.JX_GetOffSetbytes(offset);
                    buffer.AddRange(list3);
                    List<byte> list4 = new List<byte>();
                    flag = this.connectIF.JX_GetFileSegment(ref file, out list4);
                    buffer.AddRange(list4);
                    if (!this.connectIF.Get_CRC_Checked(ref buffer))
                    {
                        return false;
                    }
                    if (!this.connectIF.JX_EscapeString(ref buffer, 5))
                    {
                        return false;
                    }
                    buffer.Add(3);

                    //将buffer的内容转化成为16进制字符串序列存于command
                    string command = "";
                    foreach (byte b in buffer)
                    {
                        command = command + b.ToString("x2");
                    }
                    command = command.ToUpper();

                    List<string> commandlist = new List<string>();
                    commandlist.Add(new Global().CommandID);
                    commandlist.Add(fcmsId);
                    commandlist.Add(paramName);
                    commandlist.Add(command);
                    
                    commandlist.Add(Global.User);
                    commandlist.Add(controlSwitch);

                    this.fcmsForm = fcmsForm;

                    BackgroundWorker bw = new BackgroundWorker();
                    bw.DoWork += Bw_DoWork;
                    bw.WorkerReportsProgress = true;
                    bw.RunWorkerCompleted += Bw_RunWorkerCompleted;
                    bw.ProgressChanged += Bw_ProgressChanged;
                    bw.RunWorkerAsync(commandlist);

                    offset += 0x800;
                    buffer.Clear();
                }
                return true;

            }
            catch
            {
                return false;
            }
        }

        public bool JX_UploadFile(string filename, ref List<byte> file, string fcmsId, string paramName, string controlSwitch)
        {
            try
            {
                byte[] bytes = Encoding.ASCII.GetBytes(filename);
                List<byte> collection = new List<byte>();
                for (int i = 0; i < bytes.Length; i++)
                {
                    collection.Add(bytes[i]);
                }
                collection.Add(0x2b);
                uint offset = 0;
                bool flag = true;
                while (flag)
                {
                    List<byte> list7 = new List<byte>();
                    list7.Add(2);
                    list7.Add(0x30);
                    list7.Add(0x30);
                    list7.Add(0x31);
                    list7.Add(0x30);
                    List<byte> buffer = list7;
                    buffer.AddRange(collection);
                    List<byte> list3 = new List<byte>();
                    list3 = this.connectIF.JX_GetOffSetbytes(offset);
                    buffer.AddRange(list3);
                    List<byte> list4 = new List<byte>();
                    flag = this.connectIF.JX_GetFileSegment(ref file, out list4);
                    buffer.AddRange(list4);
                    if (!this.connectIF.Get_CRC_Checked(ref buffer))
                    {
                        return false;
                    }
                    if (!this.connectIF.JX_EscapeString(ref buffer, 5))
                    {
                        return false;
                    }
                    buffer.Add(3);

                    //将buffer的内容转化成为16进制字符串序列存于command
                    string command = "";
                    foreach (byte b in buffer)
                    {
                        command = command + b.ToString("x2");
                    }
                    command = command.ToUpper();

                    List<string> commandlist = new List<string>();
                    commandlist.Add(new Global().CommandID);
                    commandlist.Add(fcmsId);
                    commandlist.Add(paramName);
                    commandlist.Add(command);

                    commandlist.Add(Global.User);
                    commandlist.Add(controlSwitch);

                    //this.fcmsForm = fcmsForm;

                    BackgroundWorker bw = new BackgroundWorker();
                    bw.DoWork += Bw_DoWork;
                    bw.WorkerReportsProgress = true;
                    bw.RunWorkerCompleted += Bw_RunWorkerCompleted;
                    bw.ProgressChanged += Bw_ProgressChanged;
                    bw.RunWorkerAsync(commandlist);

                    offset += 0x800;
                    buffer.Clear();
                }
                return true;

            }
            catch
            {
                return false;
            }
        }

        private void Bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            string result = e.UserState as string;
            if (result == "0")
            {
                MessageBox.Show("情报板指令发送失败", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
                return;
            }
            if (fcmsForm != null)
            {
                fcmsForm.changeFcmsList();
            }
        }

        private void Bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //string result = e.Result as string;
            //if(result=="0")
            //{
            //    MessageBox.Show("情报板指令发送失败", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
            //    return;
            //}
            //if (fcmsForm != null)
            //{
            //    fcmsForm.changeFcmsList();
            //}
        }

        private void Bw_DoWork(object sender, DoWorkEventArgs e)
        {
            List<string> commandlist = e.Argument as List<string>;
            string commandId = commandlist[0];
            string fcmsId = commandlist[1];
            string paramName = commandlist[2];
            string command = commandlist[3];
            string user = commandlist[4];
            string controlswitch = commandlist[5];

            string sqlOpenSwitch= "INSERT INTO R_Command([CommandID],[DeviceID],[ParamName],[ParamValue],[UpdateTime],[UpdateBy],[Runned]) VALUES(' " + new Global().CommandID + "','" + fcmsId + "','" + controlswitch + "','" + "1" + "', GETDATE(),'" + user + "','0')";
            string sqlFcmsCommand = "INSERT INTO R_Command([CommandID],[DeviceID],[ParamName],[ParamValue],[UpdateTime],[UpdateBy],[Runned]) VALUES(' " + commandId + "','" + fcmsId + "','" + paramName + "','" + command + "', GETDATE(),'" + user + "','0')";

            string[] sqls = { sqlOpenSwitch, sqlFcmsCommand };
            SqlDBHelper sdh = new SqlDBHelper();
            int result = sdh.ExecteTranCommand(sqls);
            ((BackgroundWorker)sender).ReportProgress(30, result.ToString());

            System.Threading.Thread.Sleep(10000);
            string sqlCloseSwitch = "INSERT INTO R_Command([CommandID],[DeviceID],[ParamName],[ParamValue],[UpdateTime],[UpdateBy],[Runned]) VALUES(' " + new Global().CommandID + "','" + fcmsId + "','" + controlswitch + "','" + "0" + "', GETDATE(),'" + user + "','0')";
            sdh.ExecuteCommand(sqlCloseSwitch);
        }
    }
}
